import { useState, useEffect, useRef } from 'react';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import { Pop, RobotInfo } from '../types';

// interface BroadCast{
//   map:{
//     "grids":[[{
//       "gridType":"NULL" | "BARRIER" | "DELIVER" | "ROBOT" | "PHARMACIST" | "COLLISION",
//       "robotSerialNumber":string,
//     }]],
//     "rows":number,
//     "columns":number,
//   },
//   robotInfoMap:{
//     "123456": {
//       "position":{
//         x:number;
//         y:number;
//       },
//       "next":{"x":0,"y":0},
//       "termination":{"x":0,"y":0},
//       "robotStatus":"FREE",
//       "selfMovingNumber":0,
//       "selfQueuingNumber":0,
//       "listenedAddress":"10.237.53.85:52292",
//     },
//     "456789":{
//     }
//   },
//   popQueue{[
//      "role":string,
//      "serialNumber": string,
//      "message":string
// ]},
//   "movingNumber":213,
//   "queuingNumber":213,
//   "movingQueue":{"robots":{},"selfNumber":0,"updated":0},
//   "queuingQueues":{"0":{"robots":{},"selfNumber":4,"updated":0},"1":{"robots":{},"selfNumber":4,"updated":0}},
//   "freeQueue":{"1":{"position":{"x":49,"y":49},"next":{"x":0,"y":0},"termination":{"x":0,"y":0},
//       "robotStatus":"FREE","selfMovingNumber":0,"selfQueuingNumber":0,"listenedAddress":"10.237.53.85:52296"}},
//   "errorQueue":{},
//   "windowMap":{"0":{"x":12,"y":1},"1":{"x":17,"y":1},"2":{"x":22,"y":1},"3":{"x":27,"y":1}},
//   "deliverCoordinate":{"x":48,"y":48},
//   "freeRobotInfos":[{"position":{"x":49,"y":49},"next":{"x":0,"y":0},"termination":{"x":0,"y":0},
//       "robotStatus":"FREE","selfMovingNumber":0,"selfQueuingNumber":0,"listenedAddress":"10.237.53.85:52296"}]
// }

interface Map{
  grids:[[{
    gridType:"NULL" | "BARRIER" | "DELIVER" | "ROBOT" | "PHARMACIST" | "COLLISION",
    robotCount: number,
    robotSerialNumber:string,
  }]],
  rows:number,
  columns:number,
}

// 定义返回的数据类型，包括 robotCount 等信息
interface SockJSData {
  robotCount: number;          // 总机器人数量
  idleRobotCount: number;      // 空闲机器人数量
  robotInfoList: RobotInfo[];  // 包含序号的机器人信息列表
  isConnected: boolean;         // 连接状态
  mapData: Map | null;         // 地图数据
  popQueue: Pop[];             // 弹窗队列
}

// 自定义 Hook 实现 SockJS 数据逻辑
export function useSockJS(): SockJSData {
  const [messages, setMessages] = useState<string[]>([]);   // 保存接收到的消息
  const [robotCount, setRobotCount] = useState<number>(0);  // 总机器人数量
  const [idleRobotCount, setIdleRobotCount] = useState<number>(0); // 空闲机器人数量
  const [robotInfoList, setRobotInfoList] = useState<RobotInfo[]>([]); // 保存机器人信息
  const [isConnected, setIsConnected] = useState(false); // 用于跟踪连接状态
  const [mapData, setMapData] = useState<Map | null>(null);   // 保存地图数据
  const [popQueue, setPopQueue] = useState<Pop[]>([]);   // 保存弹窗队列

  // test
  const countRef = useRef(0);  // 使用 useRef 存储 count

  // 建立 WebSocket 连接并订阅消息
  useEffect(() => {
    const socket = new SockJS('http://192.168.42.11:4399/ws'); 
    const client = Stomp.over(socket);

    client.connect({}, (frame) => {
      console.log('Connected: ' + frame);

      client.debug = () => {};  //取消控制台输出

      // 订阅广播消息
      client.subscribe('/broadcast/test', (message) => {
        try {
          const parsedMessage = JSON.parse(message.body); // 假设消息是 JSON 格式

          // 提取信息
          const mapData: Map = parsedMessage.map || { grids: [[]], rows: 0, columns: 0 };
          const robotInfoMap: { [key: string]: Omit<RobotInfo, 'serialNumber'> } = parsedMessage.robotInfoMap || {};
          const freeQueue: { [key: string]: Omit<RobotInfo, 'serialNumber'> } = parsedMessage.freeQueue ||{};

          const robotInfoArray: RobotInfo[] = Object.entries(robotInfoMap).map(([serialNumber, robotData]) => ({
            serialNumber, // 添加机器人的序号
            ...robotData, // 解构机器人其他信息
          }));
          const idleRobotInfoArray: RobotInfo[] = Object.entries(freeQueue).map(([serialNumber, robotData]) => ({
            serialNumber, 
            ...robotData, 
          }));
          const popQueue: Pop[] = parsedMessage.popQueue || [];
          const idleRobots = idleRobotInfoArray.filter((robot) => robot.robotStatus === 'FREE');  // 统计空闲机器人

          // 更新数据
          setMapData(mapData);

          setRobotInfoList(robotInfoArray);          
          setRobotCount(robotInfoArray.length);

          setIdleRobotCount(idleRobots.length);
          
          setPopQueue(popQueue);          // 更新弹窗队列
          
          
          // **确保count递增顺序**
          setMessages((prevMessages) => {
            console.log("counttttttttttttttttttttttttttttttt", countRef.current); // 使用递增前的值
            countRef.current++;  // 递增 count
            return [...prevMessages, message.body];
          });
          // console.log("sockJS robotList",robotInfoList);
          // console.log("robotcount",robotCount);
          // console.log("idlecount",idleRobotCount);

          // 保存消息内容
          // setMessages((prevMessages) => [...prevMessages, message.body]);
        } catch (error) {
          console.error('Error parsing message:', error);
        }
      });
    });

    // 断开连接时清理资源
    return () => {
      if (client && isConnected) {
        client.disconnect(() => {
          console.log('Disconnected');
        });
      }
    };
  }, [isConnected]);

//test
  // 使用 useEffect 来监控 popQueue 的变化并打印
  useEffect(() => {
    console.log("Updated robottttttttttttttttttttttttttttt", robotInfoList);
  }, [popQueue]);

  return {
    robotCount,
    idleRobotCount,
    robotInfoList, // 返回包含序号的机器人信息列表
    isConnected,
    mapData,       // 返回地图数据
    popQueue,
  };
}
